package com.rockville.ufone.rssdata;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.apache.log4j.helpers.Loader;
import org.apache.log4j.xml.DOMConfigurator;

import com.rockville.ufone.DBProc;
import com.sun.syndication.feed.WireFeed;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class AknFeedParser implements Runnable {
	
	
	private static final Logger log = Logger.getLogger(AknFeedParser.class);
    private String feedUrl = null;
    private String feedName = null;
    private String feedId = null;    
    
    public AknFeedParser(String id, String name, String url) {
    	feedId = "1";
    	feedName = "National News";
//        feedUrl = "http://news.google.com/news?pz=1&cf=all&ned=en_pk&hl=en&topic=n&output=rss";
        feedUrl = "http://jang.net/data/rdf/jang_urdu.rdf";
        
    }

	@Override
	public void run() {		
		log.debug("("+feedId+") AknFeedParser run (" + feedUrl + ")");
		String strTitle = "", strDescp = "", strImage = "";
		Date dt_http = null;
		Date newsDate = null;
		URL feedURL = null;
		try {
			feedURL = new URL(feedUrl);
		} catch (MalformedURLException ex) {
			log.error("MalformedURLException creating feed URL: " + feedUrl, ex);
		} catch (Exception ex) {
			log.error("Exception creating feed URL: " + feedUrl, ex);
		}

		try {
			DBProc db = DBProc.getInstance();
			SyndFeedInput input = new SyndFeedInput();
			SyndFeed synfeed = input.build(new XmlReader(feedURL));

			// --log.debug("syn feed \n "+synfeed);
			WireFeed wf = synfeed.createWireFeed();
			SyndFeedImpl sfi = new SyndFeedImpl(wf);
			SyndEntryImpl sei = new SyndEntryImpl();
			// sdformatter = new SimpleDateFormat("EEE MMM dd, yyyy HH:mm:ss");
			SyndContentImpl sci = null;
			log.debug("("+feedId+") sfi PublishDate " + sfi.getPublishedDate());

			List lstFeed = synfeed.getEntries();
			ListIterator it = lstFeed.listIterator();
			Collections.reverse(lstFeed);// listFeed in reverse order
			StringBuffer strBuff = new StringBuffer();
			while (it.hasNext()) {
				sei = (SyndEntryImpl) it.next();
				sci = (SyndContentImpl) sei.getDescription();
				strTitle = sei.getTitle();
				strDescp = sci.getValue();
				log.debug("("+feedId+") Title: " + strTitle);					
				log.debug("("+feedId+") Description: " + strDescp);
				dt_http = sei.getPublishedDate();
				List cates = sei.getCategories();
				/*
				boolean updateOnly = ("94".equals(feedId) || "96".equals(feedId) || "97".equals(feedId) || "101".equals(feedId) || "103".equals(feedId));
				int index = 0;
				if("95".equals(feedId)) {
					if((index = strDescp.indexOf("\n")) > 0) {					
						strTitle = strDescp.substring(0, index);
					}
				}				
				if(cates.size() > 0 && index <= 0) {
					strTitle = ((SyndCategoryImpl)cates.get(0)).getName();
				}						
				// strXmlDate = sdformatter.format(dt_http);
				// log.debug("Publisher Date " + strXmlDate);
				if("93".equals(feedId)) {
					strBuff.append(strDescp);
					strBuff.append("\n");
				}
				else {
					if("102".equals(feedId)) {
				    	strDescp = strDescp.replaceFirst("(.*):", "<b>$1:</b>");
				    	strDescp = strDescp.replaceFirst("\\-(.*)\\-", "<div style=\"font-weight:bold;\">$1</div>");
					}
			    	strDescp = strDescp.replaceAll("\n", "<br/>");					
					db.saveNews(strTitle, strDescp, dt_http, feedId, strImage, updateOnly);
				}
				*/
                if(newsDate == null)
                	newsDate = dt_http;
                else if(dt_http.compareTo(newsDate) > 0)
                	newsDate = dt_http;
			}// end while
			/*
			if(strBuff.length() > 1) {
				strDescp = strDescp.replaceAll("\n", "<br/>");
				db.saveNews(strTitle, strBuff.toString(), newsDate, feedId, strImage, true);
			}
			db.updateChannelLastNewsDate(Integer.parseInt(feedId), newsDate);
			*/
			
		} catch (NullPointerException npex) {
			log.error("("+feedId+") Out of Memory Exception", npex);
		} catch (IOException ex) {
			log.error("("+feedId+") IOException parsing URL: " + feedUrl, ex);
		} catch (Exception ex) {
			log.error("("+feedId+") Exception parsing URL: " + feedUrl, ex);
		}
		
		/*
		SyndFeedInput input = new SyndFeedInput();
		SyndFeed synfeed = input.build(new XmlReader(feed));

		// --log.debug("syn feed \n "+synfeed);
		WireFeed wf = synfeed.createWireFeed();
		SyndFeedImpl sfi = new SyndFeedImpl(wf);
		SyndEntryImpl sei = new SyndEntryImpl();
		// sdformatter = new SimpleDateFormat("EEE MMM dd, yyyy HH:mm:ss");
		SyndContentImpl sci = null;
		log.debug("sfi Title: " + sfi.getTitle());
		log.debug("sfi Desc: " + sfi.getDescription());
		log.debug("sfi PublishedDate: " + sfi.getPublishedDate());
		log.debug("synfeed PublishedDate: " + synfeed.getPublishedDate());

		List lstFeed = synfeed.getEntries();
		ListIterator it = lstFeed.listIterator();
		while (it.hasNext()) {
			sei = (SyndEntryImpl) it.next();
			sci = (SyndContentImpl) sei.getDescription();
			String strTitle = sei.getTitle();
			String strDescp = sci.getValue();
			String category = ((SyndCategoryImpl)sei.getCategories().get(0)).getName();
			Object o = sei.getForeignMarkup();
			log.debug("Title " + strTitle);
			log.debug("Category " + category);
			log.debug("Description " + strDescp);
			log.debug("PublishedDate " + sei.getPublishedDate());
			log.debug("foreign " + o);
		}// end while
		} catch (Exception ex) {
			log.error("Exception parsing URL: ", ex);
		}
		*/
	}

	public static void main(String[] args) {
		try {
			URL url = Loader.getResource("log4j-config.xml");
			DOMConfigurator.configure(url);
			AknFeedParser parser = new AknFeedParser("", "", "");
			ExecutorService executor = Executors.newCachedThreadPool();
			executor.execute(parser);
		} catch (Exception e) {
			log.error("", e);
		}
	}
	
}
